#!/usr/llbin/python3
import yaml
import sys
import os


def merge_data(data_1, data_2):
    """
    使用 data_2 和 data_1 合成一个新的字典。
    对于 data_2 和 data_1 都有的 key，如果data_2为None，则用data_1，否则用data_2。
    :param data_1:
    :param data_2:
    :return:
    """
    if isinstance(data_1, dict) and isinstance(data_2, dict):
        new_dict = {}
        d2_keys = list(data_2.keys())
        for d1k in data_1.keys():
            if d1k in d2_keys:  # d1,d2都有。去往深层比对
                d2_keys.remove(d1k)
                new_dict[d1k] = merge_data(data_1.get(d1k), data_2.get(d1k))
            else:
                new_dict[d1k] = data_1.get(d1k)  # d1有d2没有的key
        for d2k in d2_keys:  # d2有d1没有的key
            new_dict[d2k] = data_2.get(d2k)
        return new_dict
    else:
        if data_2 is None:  # d2为空使用d1
            return data_1
        else:  # d2不为空使用d2
            return data_2


template_yml = os.path.abspath(sys.argv[2])
basePath = os.path.abspath(sys.argv[1])
with open(os.path.join(template_yml), "r") as f:
    templateJson = yaml.load(f, Loader=yaml.FullLoader)
for root, dir, files in os.walk(basePath):
    for file in files:
        if file.endswith(".yml"):
            print(root)
            with open(os.path.join(os.path.join(root, file)), "r") as f:
                data = yaml.load(f, Loader=yaml.FullLoader)
                data = merge_data(data, templateJson)
                print(data["spring"]["cloud"]["inetutils"]["ignoredInterfaces"])
            with open(os.path.join(os.path.join(root, file)), "w") as f:
                yaml.dump(data, f)
